package com.car.mgr.web.qdsl.utils;

import com.querydsl.core.Tuple;
import com.querydsl.core.types.Expression;
import com.querydsl.core.types.OrderSpecifier;
import com.querydsl.core.types.dsl.Expressions;
import java.lang.Class;
import java.lang.Integer;
import java.lang.String;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Optional;
import org.springframework.data.querydsl.QPageRequest;

public class QdslTools {
  public static int DEFAULT_PAGE_SIZE = 10;

  public static DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

  public static LocalDateTime toLocalDateTime(long millis) {
    return Instant.ofEpochMilli(millis).atZone(ZoneId.systemDefault()).toLocalDateTime();
  }

  public static LocalDateTime toLocalDateTime(String time) {
    return LocalDateTime.parse(time, FORMATTER);
  }

  public static Expression<LocalDateTime> toExpression(long millis) {
    return Expressions.constant(toLocalDateTime(millis));
  }

  public static Expression<LocalDateTime> toExpression(String time) {
    return Expressions.constant(toLocalDateTime(time));
  }

  public static <T> T getOrDefault(Tuple tuple, Expression<T> e, T val) {
    if(tuple == null) {
      return val;
    }
    return Optional.ofNullable(tuple.get(e)).orElse(val);
  }

  public static <T> T getOrDefault(Tuple tuple, int idx, Class<T> clazz, T val) {
    if(tuple == null) {
      return val;
    }
    return Optional.ofNullable(tuple.get(idx, clazz)).orElse(val);
  }

  public static QPageRequest toPageRequest(Integer page, Integer pageSize,
      OrderSpecifier... orderSpecifiers) {
    page = (page == null || page <= 0) ? 0 : page - 1;
    pageSize = (pageSize == null || pageSize <= 0) ? DEFAULT_PAGE_SIZE : pageSize;
    return new QPageRequest(page, pageSize, orderSpecifiers);
  }
}
